package com.dstz.agilebpm.base.samples.config;

import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {
	
	@Bean
	public RestTemplate restTemplate() {
		return new RestTemplate();
	}
	
	public static TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
		public void checkClientTrusted(X509Certificate[] arg0,String arg1) throws CertificateException {}
		public void checkServerTrusted(X509Certificate[] arg0,String arg1) throws CertificateException {}
		public X509Certificate[] getAcceptedIssuers() { return zero; }
		private X509Certificate[] zero = new X509Certificate[0];
	}};
	public static HostnameVerifier verifyAllHosts = new HostnameVerifier() {  
		public boolean verify(String urlHostName, SSLSession session) { return true; }  
	};
	public static SSLContext sslContext = null;
	static {
		if(!Boolean.getBoolean("ssl.defaults.noTrustAll")) {
			try{
				sslContext = SSLContext.getInstance("SSL");
				sslContext.init(null, trustAllCerts, new SecureRandom());
				HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
				HttpsURLConnection.setDefaultHostnameVerifier(verifyAllHosts);
			}catch(Exception e) {
				
			}
		}
	}
}
